package cn.gov.anhai.service;

import cn.gov.anhai.mappers.DynamicMapper;
import cn.gov.anhai.mappers.PublicMapper;
import cn.gov.anhai.mappers.UserMapper;
import cn.gov.anhai.utils.ApiResult;
import cn.gov.anhai.utils.MyUtil;
import cn.gov.anhai.utils.PageUtil;
import cn.gov.anhai.vo.OssVO;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 动态
 */
@Service
public class DynamicService {

    @Resource
    PublicMapper publicMapper;

    @Resource
    DynamicMapper dynamicMapper;

    @Resource
    UserMapper userMapper;

    @Resource
    UserService userService;

    @Resource
    PublicService publicService;

    /**
     * 查询列表
     *
     * @param current       当前页码
     * @param size          每个个数
     * @param tourismId     景点id
     * @param userId        发布用户id
     * @param collectId     收藏用户id
     * @param is_display    是否显示（0是，1否）
     * @param review_status 审核状态（0审核中 1已驳回 2审核通过）
     * @param orderType     排序类型（desc,asc）
     */
    public List<Map<String, Object>> list(Integer current, Integer size, Long tourismId, Long userId, Long collectId,
                                          Integer is_display, Integer review_status, String orderType) {
        PageUtil pageUtil = new PageUtil(current, size);
        List<Map<String, Object>> list = dynamicMapper.list(pageUtil.getOffset(), pageUtil.getRow(), tourismId, userId, collectId,
                is_display, review_status, orderType);
        list.forEach(item -> {
            OssVO cover = publicService.getOssInfo((Long) item.get("cover"));
            item.put("cover", cover.getUrl());
            item.put("previewUrl", cover.getPreviewUrl());

            item.put("size", new HashMap<String, Object>() {
                {
                    put("width", item.remove("width"));
                    put("height", item.remove("height"));
                }
            });
            item.put("avatar", publicService.getOSSUrl((Long) item.get("avatar")));
            item.put("user", new HashMap<String, Object>() {
                {
                    put("nickname", item.remove("nickname"));
                    put("avatar", item.remove("avatar"));
                }
            });
        });
        return list;
    }

    /**
     * 查询列表（个数）
     *
     * @param tourismId     景点id
     * @param userId        发布用户id
     * @param collectId     收藏用户id
     * @param is_display    是否显示（0是，1否）
     * @param review_status 审核状态（0审核中 1已驳回 2审核通过）
     */
    public Integer listCount(Long tourismId, Long userId, Long collectId, Integer is_display, Integer review_status) {
        Integer count = dynamicMapper.listCount(tourismId, userId, collectId, is_display, review_status);
        return count;
    }

    /**
     * 动态详情（公开）
     */
    public Map<String, Object> info(Long id, Long loginId, String isPrivate) {
        Map<String, Object> info = dynamicMapper.info(id);
        if (info == null) return null;
        Map<String, Object> result = new HashMap<>();
        Long uid = (Long) info.get("user_id");
        Long did = (Long) info.get("id");

        result.put("id", info.get("id"));
        Integer status = (Integer) info.get("review_status");
        if (status != 2 && !"1".equals(isPrivate)) {
            return null;
        } else if (!"1".equals(isPrivate)) {
            dynamicMapper.updateCount(id);
        }
        result.put("status", info.get("review_status"));
        result.put("title", info.get("title"));
        result.put("content", info.get("content"));
        result.put("detailType", info.get("type"));//类型（0-常规、1=官方、2=用户）
        //User
        result.put("user", userService.infoLabel(uid));
        //if (loginId != null) {
        //点赞
        result.put("like", publicService.getUserDynamic(loginId, 1, did, "isLike"));
        //收藏
        result.put("collect", publicService.getUserDynamic(loginId, 2, did, "isCollect"));
        //}
        //图片或视频
        List<String> banner_img_list = publicService.getOSSUrl((String) info.get("banner_img_list"));
        String dataFileType = MyUtil.getDataFileType(banner_img_list);
        result.put("type", dataFileType);
        if ("video".equals(dataFileType) && !banner_img_list.isEmpty()) {
            result.put("video", banner_img_list.get(0));
        } else {
            if (banner_img_list.isEmpty()) {
                Long cover = (Long) info.get("cover");
                if (cover != null) {
                    String ossUrl = publicService.getOSSUrl(cover);
                    banner_img_list.add(ossUrl);
                }
            }
            result.put("photos", banner_img_list);
        }

        return result;
    }

    /**
     * 动态详情（私人）
     */
    public Map<String, Object> infoByUserId(Long id, Long loginId) {
        Map<String, Object> info = dynamicMapper.info(id);
        if (info == null) return null;
        Long uid = (Long) info.get("user_id");
        Long did = (Long) info.get("id");
        if (!loginId.equals(uid)) return null;

        Map<String, Object> result = new HashMap<>();
        result.put("id", info.get("id"));
        result.put("status", info.get("review_status"));
        result.put("title", info.get("title"));
        result.put("content", info.get("content"));
        result.put("detailType", info.get("type"));
        result.put("cover", new HashMap<String, Object>() {
            {
                put("ossId", info.get("cover"));
                OssVO cover = publicService.getOssInfo((Long) info.get("cover"));
                put("url", cover.getUrl());
                put("previewUrl", cover.getPreviewUrl());
            }
        });

        //图片列表
        String type = null;
        List<Map<String, Object>> imgs = new ArrayList<Map<String, Object>>();
        String banner_img_list = (String) info.get("banner_img_list");
        String[] banner_img_lists = banner_img_list.split("\\,");
        for (String img : banner_img_lists) {
            Long imgId = Long.parseLong(img);
            OssVO ossInfo = publicService.getOssInfo(imgId);
            imgs.add(new HashMap<String, Object>() {
                {
                    put("ossId", imgId);
                    put("url", ossInfo.getUrl());
                    put("previewUrl", ossInfo.getPreviewUrl());
                }
            });
            if (type == null) {
                type = MyUtil.getDataFileType(ossInfo.getUrl());
            }
        }
        result.put("type", type);
        if ("video".equals(type) && imgs.size() > 0) {
            result.put("video", imgs.get(0));
        } else {
            result.put("photos", imgs);
        }

        //景点
        result.put("locationList", dynamicMapper.dynamicCountList(did));

        return result;
    }

    /**
     * 新增动态
     */
    public ApiResult<Object> add(Long uid, String title, String content,
                                 JSONArray locationList, JSONObject size, JSONArray photos, JSONObject video) {
        if (StringUtils.isEmpty(title)) ApiResult.fail("请输入必填项");
        if (StringUtils.isEmpty(content)) ApiResult.fail("请输入必填项");
        if (locationList == null) locationList = new JSONArray();
        if (photos.isEmpty() || video == null) ApiResult.fail("请最少上传一张照片或视频");

        StringBuilder address_tag = new StringBuilder();
        Long did = MyUtil.getUUID();
        for (int i = 0; i < locationList.size(); i++) {
            JSONObject json = locationList.getJSONObject(i);
            publicMapper.addDynamicCount(did, json.getLong("id"));
            address_tag.append(",").append(json.getStr("name"));
        }

        StringBuilder banner_img_list = new StringBuilder();
        Long cover = Long.MIN_VALUE;
        if (!photos.isEmpty()) {
            cover = photos.getLong(0);
            for (int i = 0; i < photos.size(); i++) {
                banner_img_list.append(",").append(photos.getLong(i));
            }
        } else if (video != null) {
            banner_img_list.append(",").append(video.getStr("videoOssId"));
            cover = video.getLong("coverOssId");
        }
        Long cover_height = 0L, cover_width = 0L;
        if (size != null) {
            cover_height = size.getDouble("height").longValue();
            cover_width = size.getDouble("width").longValue();
        }

        Integer result = dynamicMapper.add(uid, did, title, content, MyUtil.getSubstring(address_tag.toString()),
                MyUtil.getSubstring(banner_img_list.toString()), cover, cover_height, cover_width);

        if (result == 1) return ApiResult.ok(did);
        return ApiResult.fail("发布失败，请重新提交");
    }

    @Transactional
    public ApiResult<Object> add(Long did, Long uid, String title, String content,
                                 JSONArray locationList, JSONObject size, JSONArray photos, JSONObject video) {
        if (StringUtils.isEmpty(title)) ApiResult.fail("请输入必填项");
        if (StringUtils.isEmpty(content)) ApiResult.fail("请输入必填项");
        if (locationList == null) locationList = new JSONArray();
        if (photos.isEmpty() || video == null) ApiResult.fail("请最少上传一张照片或视频");

        StringBuilder address_tag = new StringBuilder();
        for (int i = 0; i < locationList.size(); i++) {
            JSONObject json = locationList.getJSONObject(i);
            publicMapper.addDynamicCount(did, json.getLong("id"));
            address_tag.append(",").append(json.getStr("name"));
        }

        StringBuilder banner_img_list = new StringBuilder();
        Long cover = Long.MIN_VALUE;
        if (!photos.isEmpty()) {
            cover = photos.getLong(0);
            for (int i = 0; i < photos.size(); i++) {
                banner_img_list.append(",").append(photos.getLong(i));
            }
        } else if (video != null) {
            banner_img_list.append(",").append(video.getStr("videoOssId"));
            cover = video.getLong("coverOssId");
        }
        Long cover_height = 0L, cover_width = 0L;
        if (size != null) {
            cover_height = size.getDouble("height").longValue();
            cover_width = size.getDouble("width").longValue();
        }

        Integer result = dynamicMapper.add(uid, did, title, content, MyUtil.getSubstring(address_tag.toString()),
                MyUtil.getSubstring(banner_img_list.toString()), cover, cover_height, cover_width);

        if (result == 1) return ApiResult.ok(did);
        return ApiResult.fail("修改失败，请重新提交");
    }

    /**
     * 修改动态
     */
    @Transactional
    public ApiResult<Object> update(Long did, Long uid, String title, String content,
                                    JSONArray locationList, JSONObject size, JSONArray photos, JSONObject video) {
        if (did == null) return ApiResult.fail("请传递修改的编号");
        Integer result = dynamicMapper.deleteByUidAndDid(uid, did);
        if (!result.equals(1)) return ApiResult.fail("修改失败0x000");
        result = publicMapper.deleteDynamicCountByDid(did);
        return add(did, uid, title, content, locationList, size, photos, video);
    }

    /**
     * 删除动态
     */
    public ApiResult<Object> delete(Long did, Long uid) {
        if (did == null) return ApiResult.fail("请传递删除的编号");
        Integer result = dynamicMapper.deleteByUidAndDid(uid, did);
        if (!result.equals(1)) return ApiResult.fail("提交失败0x001");
        result = publicMapper.deleteDynamicCountByDid(did);
        return ApiResult.ok("移除成功");
    }

    /**
     * 收藏动态信息
     */
    public Map<String, Object> doCollect(Long uid, Long did) {
        return publicService.doUserDynamic(uid, 2, did, "isCollect");
    }

    /**
     * 点赞动态信息
     */
    public Map<String, Object> doLike(Long uid, Long did) {
        return publicService.doUserDynamic(uid, 1, did, "isLike");
    }
}
